/*
 * @Date: 2023-03-01 22:17:36
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-04-13 10:57:38
 */
import { defineStore } from 'pinia'
import { userLogin, userLoginout, initCache } from '@/api/user/login'
import { getUserPermission, getUserInfo } from '@/api/user/account'
import { cookiesStorage } from '@/utils/bussTool'
import { setSessionItem } from '@/utils/baseTool'
import { appStore } from '@/stores/app'
import config from '@/config'
const access: any = ['super_admin', 'admin']

export const userStore = defineStore(`${config.sysCode}_user`, {
  state: (): any => {
    return {
      userInfo: {}, // 用户信息
      token: '',
      sidToken: '',
      access: [],
      hasGetInfo: false, // 是否获取用户信息
      permissionList: [] // 用户权限按钮列表
      // isSimplePwd: false,
    }
  },
  persist: {
    enabled: true,
    strategies: [
      { storage: cookiesStorage, paths: ['token', 'sidToken'] },
      { storage: localStorage, paths: ['permissionList'] }
    ]
  },
  getters: {
    // 登录名
    loginName(state) {
      return state.userInfo.loginName
    },
    // 用户id
    userId(state) {
      return state.userInfo.id
    },
    // 用户名
    userName(state) {
      return state.userInfo.name
    },
    // 所在部门id
    userDepartId(state) {
      return state.userInfo.userDepartId
    },
    // 所在部门名称
    userDepartName(state) {
      return state.userInfo.userDepartName
    },
    // 所在机构id
    userUnitId(state) {
      return state.userInfo.userUnitId
    },
    // 所在机构名称
    userUnitName(state) {
      return state.userInfo.userUnitName
    },
    // 所属机构所在地区
    userUnitAreacode(state) {
      return state.userInfo.userUnitAreacode
    },
    // 所属机构所在地区
    userUnitAreacodeName(state) {
      return state.userInfo.userUnitAreacodeName
    },
    // 是否监察系统用户
    isJcSystem(state) {
      return state.userInfo.industryType === '21'
    }
  },
  actions: {
    // 用户信息赋值统一处理
    userInfoSetHandle(userInfo: any) {
      this.userInfo = userInfo
      if (userInfo?.jurisdiction) {
        this.userInfo.userUnitAreacode = userInfo.jurisdiction
      }

      this.token = userInfo.userSsoInfo
      this.sidToken = userInfo.sessionid || userInfo.sessionId
      this.access = userInfo.access || access
      this.hasGetInfo = true
    },
    // 登录
    loginHandle(username: string, password: string, validateCode?: string) {
      return new Promise((resolve, reject) => {
        userLogin({
          username: username.trim(),
          password,
          validateCode,
          loginType: '1'
        })
          .then((res) => {
            const { isSuccess, errorMsg, errmsg, user, sessionid } = res
            if (isSuccess) {
              // commit('setIsSimplePwd', isSimplePwd(password) < 3)
              // if(isSimplePwd(password) < 3){
              //   alert(password + "密码过于简单，请及时修改");
              // }

              user.sessionid = sessionid
              this.userInfoSetHandle(user)
              this.hasGetInfo = true

              // 权限获取
              this.getPermissionListHandle()
              // 可存储数据获取
              this.getInitCache()

              resolve(user)
            } else {
              reject(errorMsg || errmsg)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 获取用户相关信息
    userInfoHandle() {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            const { isSuccess, errorMsg, errmsg, data } = res
            if (isSuccess) {
              this.userInfoSetHandle(data)
            } else {
              window.$Message.error(errorMsg || errmsg)
            }
            resolve(data)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 退出登录
    loginoutHandle() {
      return new Promise((resolve, reject) => {
        userLoginout()
          .then((res) => {
            this.token = ''
            this.sidToken = ''
            this.access = []
            this.hasGetInfo = false
            this.permissionList = []

            const _appStore = appStore()
            _appStore.NavTagsResetHandle()
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 获取各菜单下按钮权限列表
    getPermissionListHandle() {
      getUserPermission().then((res) => {
        const { isSuccess, errorMsg, errmsg, data } = res || {}
        if (isSuccess) {
          this.permissionList = data
        } else {
          window.$Message.error(errorMsg || errmsg)
        }
      })
    },
    // 获取可以存储的系统数据
    getInitCache() {
      initCache().then((res) => {
        const { isSuccess, data, idList } = res
        if (isSuccess) {
          idList.forEach((id: string) => {
            setSessionItem(id, data[id])
          })
        }
      })
    }
  }
})
